package pro.softzhang.algo.lc100;

import pro.softzhang.algo.common.TreeNode;
import pro.softzhang.algo.flag.knowledge.KBinaryTree;
import pro.softzhang.algo.flag.x.XOptimal;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 基本操作
 * 层序遍历
 */
@KBinaryTree
public class LC102_BinaryTreeLevelOrderTraversal {
    public static void main(String[] args) {

    }

    /**
     * 队列写法
     */
    @XOptimal
    static
    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> r = new ArrayList<>();
            if (root == null) return r;

            Queue<TreeNode> q = new LinkedList<TreeNode>(){{
                offer(root);
            }};
            while (!q.isEmpty()) {
                int counter = q.size();
                List<Integer> l = new ArrayList<>();
                while (counter-- > 0) {
                    TreeNode n = q.poll();
                    l.add(n.val);
                    if (n.left != null) {
                        q.offer(n.left);
                    }
                    if (n.right != null) {
                        q.offer(n.right);
                    }
                }
                r.add(l);
            }
            return r;
        }
    }
}
